package com.wframe.project.jnd.wx.controller;

import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.jnd.entity.FlashSalePromotion;
import com.wframe.project.jnd.services.CouponService;
import com.wframe.project.jnd.vo.Product;
import com.wframe.project.jnd.entity.Promotion;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.services.FloorService;
import com.wframe.project.jnd.services.ProductService;
import com.wframe.project.jnd.services.PromotionService;
import com.wframe.project.jnd.util.PromotionBuilderFactory;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.wx.constant.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created by lwb on 2017/4/13.
 */
@RequestMapping("/we/product")
@Controller
public class WechatProductController extends BaseController {

    @Autowired
    private ProductService productService;

    @Autowired
    private FloorService floorService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private CouponService couponService;

    /**
     * 商品详情
     *
     * @param priceid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{priceid}", method = RequestMethod.GET)
    public String info(@PathVariable String priceid, Model model) throws Exception {
        Product product = productService.findPowerProduct(priceid);
        if (product == null) {
            model.addAttribute("isSale", false);//下架
            return "/wesite/view/product/detail";
        }

        Product result = productService.findOne(priceid);//商品基本信息
        result.setAmount(product.getAmount());

        SessionUser loginUser = WebSession.getWbUser(session);
        if (loginUser != null) {
            String userid = loginUser.getUserid();
            if (WebSession.checkWbUserAuth(userid)) {
                //商品优惠券列表
                model.addAttribute("coupons", couponService.findAll(userid, priceid, Promotion.Platform.WE.ordinal()));

                product = productService.findPowerProduct(userid, priceid);
                result.setPrice(product.getPrice());//价格等级
                result.setFavorite(product.isFavorite());//收藏
                result.setControl(product.isControl());//控销

                Map<String, Promotion> promotionMap = new HashMap<>();
                Map<String, String> promotions = promotionService.findAll(priceid, userid, Promotion.Platform.WE.ordinal());//商品促销信息
                String key = Promotion.Type.FLASH_SALE.name();
                if (promotions.containsKey(key)) {
                    //单品促销信息
                    FlashSalePromotion flashSale = (FlashSalePromotion) promotionService.findFlashSale(userid, promotions.get(key));
                    if (Objects.nonNull(flashSale) && flashSale.getAmount() > 0) {
                        //单品促销有库存
                        promotionMap.put(key.toLowerCase(), flashSale);

                        int amount = flashSale.getAmount();
                        int inventory = result.getAmount();
                        result.setAmount(amount > inventory ? inventory : amount);
                    }
                    //单品促销无库存
                    promotions.remove(key);
                }

                if (!promotions.isEmpty()) {
                    Set<Map.Entry<String, String>> entries = promotions.entrySet();
                    Iterator<Map.Entry<String, String>> iterator = entries.iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> next = iterator.next();
                        String type = next.getKey();
                        promotionMap.put(type.toLowerCase(), PromotionBuilderFactory.get(type).build(next.getValue()));
                    }
                }
                model.addAttribute("wePromotions", promotionMap);
            }
        }

        productService.addpopularity(priceid);
        model.addAttribute("isSale", true);
        model.addAttribute("bean", result);
        return "/wesite/view/product/detail";
    }

    /**
     * 加载商品列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "WeList")
    public String list(String clscode, String attritems, Integer ordertype, Integer orderby, Integer instock, String querylike, String floorid, String flooritemid, HttpServletRequest request, Model model) throws Exception {
        if (StringUtils.isBlank(clscode)) {
            clscode = "1";
        }
        String keyword = "";
        if (StringUtils.isNotBlank(querylike)) {
            querylike = querylike.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            keyword = URLDecoder.decode(querylike, "UTF-8");
        }
        model.addAttribute("subclslist", productService.getProductSubCls(clscode));
        String[] seleditems = null;
        if (StringUtils.isNotBlank(attritems)) {
            seleditems = attritems.split(",");
        }
        List<Map> attrlist = productService.getAttrs(clscode, seleditems);
        model.addAttribute("attrlist", attrlist);//属性列表
        model.addAttribute("clscode", clscode);
        model.addAttribute("clsnavs", productService.queryClsNav(clscode));//已选分类信息
        List<Map> attrNavs = null;
        if (seleditems != null) {
            attrNavs = productService.queryAttrNav(seleditems);//已选属性信息
        }
        if (StringUtils.isNotBlank(floorid) || StringUtils.isNotBlank(flooritemid)) {
            if (attrNavs == null) {
                attrNavs = new ArrayList<Map>();
            }
            if (StringUtils.isNotBlank(flooritemid)) {
                JdataBean flooritem = floorService.getFloorItem(flooritemid);
                if (flooritem != null) {
                    Map flooritemmap = new HashMap();
                    flooritemmap.put("attrname", "类目");
                    flooritemmap.put("text", flooritem.getString("name"));
                    flooritemmap.put("id", "flooritem_" + flooritemid);
                    attrNavs.add(0, flooritemmap);
                }
            }
            if (StringUtils.isNotBlank(floorid)) {
                JdataBean floor = floorService.getFloor(floorid);
                if (floor != null) {
                    Map floormap = new HashMap();
                    floormap.put("attrname", "楼层");
                    floormap.put("text", floor.getString("id") + "F");
                    floormap.put("id", "floor_" + floorid);
                    attrNavs.add(0, floormap);
                }
            }
        }
        int pageno = 1;
        if (StringUtils.isNotBlank(request.getParameter("pno"))) {
            pageno = Integer.parseInt(request.getParameter("pno"));
        }
        model.addAttribute("attrnavs", attrNavs);
        model.addAttribute("pageno", pageno);
        model.addAttribute("ordertype", ordertype);
        model.addAttribute("orderby", orderby);
        model.addAttribute("instock", instock);
        model.addAttribute("querylike", keyword);
        model.addAttribute("floorid", floorid);
        model.addAttribute("flooritemid", flooritemid);
        return "/wesite/view/product/list";
    }

    /**
     * 加载商品列表数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/WeLoadproducts")
    public void loadproducts(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean parms = WebUtils.requestMapToBean(request.getParameterMap());
            int pageno = 1;
            if (StringUtils.isNotBlank(request.getParameter("pno"))) {
                pageno = Integer.parseInt(request.getParameter("pno"));
            }
            PageResult pr = productService.queryWebProduct(parms, Constant.DEFAULT_PAGE_SIZE, pageno);
            if (WebSession.checkLoginStatus(request.getSession())) {
                parms.put("userId", WebSession.getWbUser(request.getSession()).getUserid());
                pr = productService.findWebProducts(parms, Constant.DEFAULT_PAGE_SIZE, pageno, 2);
            }
            JdataBean redata = new JdataBean();
            redata.put("products", pr.getList());
            redata.put("pagecount", pr.getPageCount());
            redata.put("resultcount", pr.getResultCount());
            redata.put("pagelist", WebUtils.toPageBean(pr, 7));
            json.putData(redata);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

}